﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace HmLab.Func2;

internal class LbCollectMonthInput {

  /// <summary>
  /// CollectInput(AppEnvPath
  /// <see cref="Haimen.Func2.MonthInputCollector"/>
  /// </summary>
  public void Run() {
    Console.WriteLine("TODO:LbCollectMonthInputLbCollectMonthInput");

    string storeDir = @"D:\work\personal\nina\2023haimen2\workshop_cslab\输O入0216f2\店铺分表";
    CopyCfg[] cfgList = [
      new("粤垦店", "粤垦", 1),
      new("东圃店", "东圃", 2),
    ];

    // 固定顺序方便测试
    var DirectoryGetFiles = () => Directory.GetFiles(storeDir)
      .Order()
      .Take(cfgList.Length);

    Dictionary<string, CopyCfg> cfgDict = cfgList.ToDictionary(c => c.File);
    var MakeInput = (string p, string file) => {
      (string month, string key) = GetStoreInfo(file);
      //Console.WriteLine($"****keykekey {store}");
      CopyCfg cfg = cfgDict[key];
      string[] input = [p, month, cfg.File, cfg.Sheet];
      return (input, sort: cfg.Sort);
    };

    string[][] inputList = DirectoryGetFiles()
      .Select(p => (path: p, file: Path.GetFileName(p)))
      .Where(tp => !tp.file.StartsWith("~$"))
      .Select(tp => MakeInput(tp.path, tp.file))
      .OrderBy(tp => tp.sort)
      .Select(tp => tp.input)
      .ToArray();

    foreach (var input in inputList) {
      Console.WriteLine(string.Join(',', input));
    }
  }

  (string, string) GetStoreInfo(string file) {
    int index = file.IndexOf("_人民币(");
    string[] infoSplit = file[..index].Split('_');

    string date = infoSplit[0];
    var GetMonth = () => {
      int start = date.IndexOf('年') + 1;
      int end = date.LastIndexOf("期月报");
      return date[start..end] + "月";
    };

    string key = infoSplit[2];
    return (GetMonth(), key);
  }

  record CopyCfg(string File, string Sheet, int Sort);
}
